<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="dtName">
        <el-input
          v-model="queryParams.dtName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="dtType">
        <el-select
          v-model="queryParams.dtType"
          placeholder="请选择任务类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_TASK_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="dtReleaseStatus">
        <el-select
          v-model="queryParams.dtReleaseStatus"
          placeholder="请选择发布状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_TASK_RELEASE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:task:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:task:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" type="index" header-align="center" align="center" width="60px" fixed />
      <el-table-column label="任务名称" align="center" prop="dtName" />
      <el-table-column label="任务类型" align="center" prop="dtType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_TASK_TYPE" :value="scope.row.dtType" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="dtBeginDate" :formatter="dateFormatter2" />
      <el-table-column label="结束时间" align="center" prop="dtEndDate" :formatter="dateFormatter2" />
      <el-table-column label="任务发布时间" align="center" prop="dtReleaseTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="发布状态" align="center" prop="dtReleaseStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_TASK_RELEASE_STATUS" :value="scope.row.dtReleaseStatus" />
        </template>
      </el-table-column>
      <el-table-column label="周期" align="center" prop="dtPeriodType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_TASK_PERIOD_TYPE" :value="scope.row.dtPeriodType" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator">
        <template #default="scope">
          {{ userList.find((user) => user.id === scope.row.creator)?.nickname }}
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="160">
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-if="scope.row.dtReleaseStatus === 1"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:task:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            v-if="scope.row.dtReleaseStatus === 2"
            @click="handleShare(scope.row.id)"
            v-hasPermi="['system:task:update']"
          >
            分享
          </el-button>
          <!-- <el-button
            link
            type="primary"
            v-if="scope.row.dtReleaseStatus === 2"
            @click="details(scope.row.id)"
            v-hasPermi="['system:task:update']"
          >
            填报
          </el-button> -->
          <el-button
            link
            type="danger"
            v-if="scope.row.dtReleaseStatus === 1"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:task:delete']"
          >
            删除
          </el-button>
          <el-dropdown
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'system:task:release',
              'system:task:revoke',
              'system:task:data-log'
            ]"
          >
            <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  command="handleRelease"
                  v-if="checkPermi(['system:task:release']) && scope.row.dtReleaseStatus !== 2"
                >
                  发布
                </el-dropdown-item>
                <el-dropdown-item
                  command="handleRevoke"
                  v-if="checkPermi(['system:task:revoke']) && scope.row.dtReleaseStatus === 2"
                >
                  撤回
                </el-dropdown-item>
                <el-dropdown-item
                  command="handleDataLog"
                  v-if="checkPermi(['system:task:data-log'])"
                >
                  数据查看
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TaskForm ref="formRef" @success="getList" />
  
  <!-- 表单弹窗：填报 -->
  <ShareForm ref="shareRef" @success="getList" />
  
  <!-- 表单弹窗：填报 -->
  <SubmitForm ref="detailRef" @success="getList" />
  
  <!-- 表单弹窗：填报 -->
  <TaskFillLog ref="datalogRef" style="width: 65%;" @success="getList" />
</template>

<script setup lang="ts">
import { TaskApi, TaskVO } from '@/api/system/task'
import * as UserApi from '@/api/system/user'

import { DICT_TYPE } from '@/utils/dict'
import { getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { checkPermi } from '@/utils/permission'

import TaskForm from './TaskForm.vue'
import ShareForm from './ShareForm.vue'
import SubmitForm from './SubmitForm.vue'
import TaskFillLog from './TaskFillLog.vue'

/** 表单任务 列表 */
defineOptions({ name: 'Task' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TaskVO[]>([]) // 列表的数据
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dtName: undefined,
  dtType: undefined,
  dtReleaseStatus: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 添加/修改操作 */
const shareRef = ref()
const handleShare = (id?: number) => {
  shareRef.value.open(id)
}

/** 查看详情 */
const detailRef = ref()
const detailId = ref()
const details = (id: number) => {
  // 打开详情视图并设置当前 id
  detailRef.value.open(id);
  detailId.value = id;
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TaskApi.deleteTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskApi.exportTask(queryParams)
    download.excel(data, '表单任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: TaskVO) => {
  switch (command) {
    case 'handleRelease':
      handleRelease(row.id)
      break
    case 'handleRevoke':
      handleRevoke(row.id)
      break
    case 'handleDataLog':
      handleDataLog(row.id)
      break
    default:
      break
  }
}

/** 发布按钮操作 */
const handleRelease = async (id: number) => {
  try {
    // 发布的二次确认
    await message.relConfirm()
    // 发起发布
    await TaskApi.releaseTask(id)
    message.success(t('common.relSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 撤回按钮操作 */
const handleRevoke = async (id: number) => {
  try {
    // 撤回的二次确认
    await message.revConfirm()
    // 发起撤回
    await TaskApi.revokeTask(id)
    message.success(t('common.revSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const datalogRef = ref()
const handleDataLog = async (id: number) => {
  // 打开详情视图并设置当前 id
  datalogRef.value.open(id)
}


/** 初始化 **/
onMounted(async () => {
  getList()
  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
})
</script>